package com.sky.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Configuration// 配置类，用于配置RedisTemplate（新）
public class RedisConfig {

    // 自定义LocalDateTime序列化和反序列化格式
    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");// 自定义日期格式

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        log.info("初始化RedisTemplate");
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();// 初始化RedisTemplate
        redisTemplate.setConnectionFactory(redisConnectionFactory);// 设置Redis连接工厂

        // 创建Jackson2JsonRedisSerializer，指定序列化目标类型（Object）
        Jackson2JsonRedisSerializer<Object> jacksonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();

        // 注册JavaTimeModule，支持LocalDateTime/LocalDate等Java 8日期类型
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // 序列化：将LocalDateTime转为指定格式的字符串
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DATETIME_FORMATTER));
        // 反序列化：将指定格式的字符串转为LocalDateTime（新增此配置解决反序列化问题）
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DATETIME_FORMATTER));
        objectMapper.registerModule(javaTimeModule);

        // 支持反序列化时识别类型（避免List/Map等集合类型丢失泛型）
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSerializer.setObjectMapper(objectMapper);

        // 配置RedisTemplate的序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer()); // Key用String序列化
        redisTemplate.setValueSerializer(jacksonSerializer); // Value用Jackson序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer()); // HashKey用String序列化
        redisTemplate.setHashValueSerializer(jacksonSerializer); // HashValue用Jackson序列化

        redisTemplate.afterPropertiesSet();// 初始化RedisTemplate，设置序列化器，afterPropertiesSet()方法会调用setters方法，设置序列化器
        return redisTemplate;
    }
}
